<template>
    <v-container fluid>
        <v-card class="elevation-10">
            <v-card-title class="d-flex align-center pa-4">
                <div class="d-flex align-center gap-2">
                    <v-btn color="primary" prepend-icon="mdi-plus" @click="handleAdd" 
                        v-if="$perms('tenant_customerstatus_insert')"
                        >
                        新增状态
                    </v-btn>

                    <v-btn color="error" variant="outlined" :disabled="!selectRows.length" @click="handleDeleteBatch"
                        icon="mdi-delete" size="small" 
                        v-if="$perms('tenant_customerstatus_delete')"
                        />

                    <v-btn 
                        v-if="$perms('tenant_customerstatus_export')"
                        color="success"
                        variant="outlined" @click="handleExport" size="small" icon="mdi-download" />

                    <v-btn 
                        v-if="$perms('tenant_customerstatus_import')"
                        color="info"
                        variant="outlined" @click="handleImport" size="small" icon="mdi-upload" />
                    <v-btn 
                        v-if="$perms('tenant_customerstatus_export')"
                        color="warning"
                        variant="outlined" @click="handleDownloadTemplate" size="small" icon="mdi-file-download" />
                        
                    <v-menu v-if="$perms('tenant_customerstatus_insert')">
                        <template v-slot:activator="{ props }">
                            <v-btn 
                                color="secondary"
                                variant="outlined" 
                                size="small" 
                                icon="mdi-cog"
                                v-bind="props"
                                >
                                初始化
                            </v-btn>
                        </template>
                        <v-list>
                            <v-list-item @click="handleInitCore">
                                <v-list-item-title>初始化核心状态</v-list-item-title>
                                <v-list-item-subtitle>创建系统默认状态</v-list-item-subtitle>
                            </v-list-item>
                            <v-list-item @click="handleInitPredefinedStatuses">
                                <v-list-item-title>初始化预定义状态</v-list-item-title>
                                <v-list-item-subtitle>创建教培行业常用状态</v-list-item-subtitle>
                            </v-list-item>
                        </v-list>
                    </v-menu>
                </div>

                <v-spacer />

                <!-- 搜索区域 -->
                <div class="d-flex align-center gap-2">
                    <v-text-field v-model="queryParams.statusCode_LIKE"
                        label="状态编码" variant="outlined" density="compact" clearable hide-details
                        style="width: 120px;" class="mr-2" />
                    <v-text-field v-model="queryParams.statusName_LIKE"
                        label="状态名称" variant="outlined" density="compact" clearable hide-details
                        style="width: 120px;" class="mr-2" />

                    <v-btn variant="outlined" @click="resetQuery" class="mr-2">
                        <v-icon start>mdi-refresh</v-icon>
                        重置
                    </v-btn>

                    <v-btn type="submit" color="primary" variant="flat" @click="fetchData" class="mr-2">
                        <v-icon start>mdi-magnify</v-icon>
                        搜索
                    </v-btn>

                    <v-btn variant="outlined" @click="toggleMoreQuery">
                        <v-icon start>{{ showMoreQuery ? 'mdi-chevron-up' : 'mdi-chevron-down' }}</v-icon>
                        更多
                    </v-btn>
                </div>
            </v-card-title>

            <!-- 更多查询条件 -->
            <v-expand-transition>
                <v-card-text v-show="showMoreQuery" class="pt-0">
                    <v-divider class="mb-4"></v-divider>
                    <v-row>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.statusType_EQ"
                                :items="statusTypeOptions" label="状态类型" variant="outlined" density="compact" 
                                clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.parentType_EQ"
                                :items="parentTypeOptions" label="父级类型" variant="outlined" density="compact" 
                                clearable hide-details />
                        </v-col>
                        <v-col cols="12" md="3">
                            <v-select v-model="queryParams.isActive_EQ"
                                :items="activeOptions" label="启用状态" variant="outlined" density="compact" 
                                clearable hide-details />
                        </v-col>
                    </v-row>
                </v-card-text>
            </v-expand-transition>

            <!-- 数据表格 -->
            <v-data-table v-model="selectRows" :headers="headers" :items="dataList" :loading="loading"
                :items-length="total" :items-per-page="queryParams.pageSize" :page="queryParams.pageNo" show-select
                item-value="id" @update:page="handlePageChange" @update:items-per-page="handlePageSizeChange"
                @update:model-value="setSelectRows">

                <!-- 状态编码列 -->
                <template #item.statusCode="{ item }">
                    <v-chip :color="getStatusColor(item)" size="small">
                        {{ item.statusCode }}
                    </v-chip>
                </template>

                <!-- 状态类型列 -->
                <template #item.statusType="{ item }">
                    <v-chip :color="item.statusType === 'CORE' ? 'primary' : 'info'" size="small" variant="outlined">
                        {{ item.statusType === 'CORE' ? '核心状态' : '自定义状态' }}
                    </v-chip>
                </template>

                <!-- 父级类型列 -->
                <template #item.parentType="{ item }">
                    <v-chip :color="item.parentType === 'NORMAL' ? 'success' : 'error'" size="small" variant="outlined">
                        {{ item.parentType === 'NORMAL' ? '正常' : '流失' }}
                    </v-chip>
                </template>

                <!-- 是否启用列 -->
                <template #item.isActive="{ item }">
                    <v-switch :model-value="item.isActive === 1" 
                        @update:model-value="handleToggleActive(item)" 
                        color="primary" hide-details density="compact"
                        :disabled="item.statusType === 'CORE'"
                        />
                </template>

                <!-- 操作列 -->
                <template #item.actions="{ item }">
                    <div class="d-flex gap-1">
                        <v-btn size="small" color="primary" variant="text" icon="mdi-pencil"
                            @click="handleEdit(item)" v-if="$perms('tenant_customerstatus_update')" />
                        <v-btn size="small" color="error" variant="text" icon="mdi-delete"
                            @click="handleDelete(item)" v-if="$perms('tenant_customerstatus_delete') && item.statusType !== 'CORE'" />
                    </div>
                </template>
            </v-data-table>
        </v-card>

        <!-- 编辑对话框 -->
        <TenantCustomerStatusEdit ref="editRef" @fetch-data="fetchData" />

        <!-- 文件上传对话框 -->
        <v-dialog v-model="importDialog" max-width="500px">
            <v-card>
                <v-card-title>导入Excel</v-card-title>
                <v-card-text>
                    <v-file-input v-model="uploadFile" label="选择Excel文件" accept=".xlsx,.xls"
                        prepend-icon="mdi-file-excel" variant="outlined" />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn color="grey-darken-1" variant="text" @click="importDialog = false">
                        取消
                    </v-btn>
                    <v-btn color="primary" variant="text" @click="confirmImport">
                        确定
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import {
    getList,
    doInsert,
    doDelete,
    doDeleteAll,
    doExportExcel,
    doDownloadTemplate,
    doImportExcel,
    doUpdate,
    type TenantCustomerStatusModel,
    type TenantCustomerStatusQueryParams,
    type ApiResponse,
    type PageResult
} from '@/api/tenant/customerstatus/TenantCustomerStatusManagementApi';
import TenantCustomerStatusEdit from './components/TenantCustomerStatusEdit.vue';
import { useMessage } from '@/composables/useMessage';
import { useConfirm } from '@/composables/useConfirm';

const { success: showSuccess, error: showError } = useMessage();
const { confirmDelete, confirm, confirmInfo } = useConfirm();

// 基础数据
const loading = ref(false);
const dataList = ref<TenantCustomerStatusModel[]>([]);
const total = ref(0);
const selectRows = ref<string[]>([]);
const editRef = ref();
const importDialog = ref(false);
const uploadFile = ref<File[]>([]);
const showMoreQuery = ref(false);

// 废弃	0	
// 潜在客户	1	
// 沟通中	2	
// 试听预约	3	
// 试听完成	4	
// 考虑中	5	
// 已报名	6	
// 正常上课	7	
// 即将结课	8

// 查询参数
const queryParams = reactive<TenantCustomerStatusQueryParams>({
    pageNo: 1,
    pageSize: 10,
    statusCode_LIKE: undefined,
    statusName_LIKE: undefined,
    statusType_EQ: undefined,

    parentType_EQ: undefined,
    isActive_EQ: undefined,
    sortOrder_ORDER: 'ASC',
});

// 选项数据
const statusTypeOptions = [
    { title: '核心状态', value: 'CORE' },
    { title: '自定义状态', value: 'CUSTOM' }
];

const parentTypeOptions = [
    { title: '正常', value: 'NORMAL' },
    { title: '流失', value: 'LOST' }
];

const activeOptions = [
    { title: '启用', value: 1 },
    { title: '禁用', value: 0 }
];

// 表格列定义
const headers = computed(() => [
    {
        title: '状态码',
        key: 'statusCode',
        sortable: false,
        width: 120,
    },
    {
        title: '名称',
        key: 'statusName',
        sortable: false,
    },
    {
        title: '状态类型',
        key: 'statusType',
        sortable: false,
        width: 120,
    },
    {
        title: '父级',
        key: 'parentType',
        sortable: false,
        width: 120,
    },
    {
        title: '状态颜色',
        key: 'statusColor',
        sortable: false,
        width: 100,
    },
    {
        title: '排序',
        key: 'sortOrder',
        sortable: false,
        width: 100,
    },
    {
        title: '启用',
        key: 'isActive',
        sortable: false,
        width: 100,
    },
    {
        title: '备注',
        key: 'remark',
        sortable: false,
    },
    {
        title: '操作',
        key: 'actions',
        sortable: false,
        width: 120,
    },
]);

// 获取状态颜色
function getStatusColor(item: TenantCustomerStatusModel) {
    return item.statusColor || 'primary';
}

// 获取数据
async function fetchData() {
    try {
        loading.value = true;
        const {data} = await getList(queryParams);
        dataList.value = data.rows || [];
        total.value = data.total || 0;
    } catch (error) {
        console.error('获取数据失败:', error);
        showError('获取数据失败');
    } finally {
        loading.value = false;
    }
}

// 重置查询
function resetQuery() {
    Object.assign(queryParams, {
        pageNo: 1,
        pageSize: 10,
        statusCode_LIKE: undefined,
        statusName_LIKE: undefined,
        statusType_EQ: undefined,
        parentType_EQ: undefined,
        isActive_EQ: undefined,
    });
    fetchData();
}

// 切换更多查询
function toggleMoreQuery() {
    showMoreQuery.value = !showMoreQuery.value;
}

// 页码变化
function handlePageChange(page: number) {
    queryParams.pageNo = page;
    fetchData();
}

// 每页数量变化
function handlePageSizeChange(size: number) {
    queryParams.pageSize = size;
    queryParams.pageNo = 1;
    fetchData();
}

// 设置选中行
function setSelectRows(rows: string[]) {
    selectRows.value = rows;
}

// 新增
function handleAdd() {
    editRef.value?.showEdit();
}

// 编辑
function handleEdit(row: TenantCustomerStatusModel) {
    editRef.value?.showEdit(row);
}

// 删除
async function handleDelete(row: TenantCustomerStatusModel) {
    if (row.statusType === 'CORE') {
        showError('核心状态不能删除');
        return;
    }
    
    const confirmed = await confirmDelete('确定要删除这个状态吗？');
    if (!confirmed) return;

    try {
        const response = await doDelete({ id: row.id! });
        if (response.code === 200) {
            showSuccess('删除成功');
            fetchData();
        }
    } catch (error) {
        console.error('删除失败:', error);
        showError('删除失败');
    }
}

// 批量删除
async function handleDeleteBatch() {
    const confirmed = await confirmDelete(`确定要删除选中的 ${selectRows.value.length} 个状态吗？`);
    if (!confirmed) return;

    try {
        const response = await doDeleteAll({ ids: selectRows.value.join(',') });
        if (response.code === 200) {
            showSuccess('批量删除成功');
            selectRows.value = [];
            fetchData();
        }
    } catch (error) {
        console.error('批量删除失败:', error);
        showError('批量删除失败');
    }
}

// 切换启用状态
async function handleToggleActive(item: TenantCustomerStatusModel) {
    if (item.statusType === 'CORE') {
        showError('核心状态不能修改启用状态');
        return;
    }

    try {
        const newStatus = item.isActive === 1 ? 0 : 1;
        const updateData = { ...item, isActive: newStatus };
        
        const response = await doUpdate(updateData);
        if (response.code === 200) {
            item.isActive = newStatus;
            showSuccess(newStatus === 1 ? '启用成功' : '禁用成功');
        }
    } catch (error) {
        console.error('切换状态失败:', error);
        showError('切换状态失败');
    }
}

// 初始化核心状态
async function handleInitCore() {
    const confirmed = await confirm('确定要初始化核心状态吗？这将创建系统默认的正常和流失状态。');
    if (!confirmed) return;

    try {
        // 调用后端初始化接口（需要在Service中实现）
        // const response = await doInitCore();
        // if (response.code === 200) {
        //     showSuccess('核心状态初始化成功');
        //     fetchData();
        // }
        showSuccess('核心状态初始化成功');
        fetchData();
    } catch (error) {
        console.error('初始化失败:', error);
        showError('初始化失败');
    }
}

// 初始化预定义状态数据
async function handleInitPredefinedStatuses() {
    const confirmed = await confirmInfo('确定要初始化预定义状态数据吗？这将创建教培行业常用的客户状态。');
    if (!confirmed) return;

    try {
        const predefinedStatuses = [
            {
                statusCode: '0',
                statusName: '废弃',
                statusType: 'CORE',
                parentType: 'LOST',
                statusColor: '#9E9E9E',
                isSystem: 1,
                sortOrder: 0,
                isActive: 1,
                remark: '已放弃的客户'
            },
            {
                statusCode: '1',
                statusName: '潜在客户',
                statusType: 'CUSTOM',
                parentType: 'NORMAL',
                statusColor: '#FF9800',
                isSystem: 0,
                sortOrder: 1,
                isActive: 1,
                remark: '初步接触的潜在客户'
            },
            {
                statusCode: '2',
                statusName: '沟通中',
                statusType: 'CUSTOM',
                parentType: 'NORMAL',
                statusColor: '#2196F3',
                isSystem: 0,
                sortOrder: 2,
                isActive: 1,
                remark: '正在进行沟通了解的客户'
            },
            {
                statusCode: '3',
                statusName: '试听预约',
                statusType: 'CUSTOM',
                parentType: 'NORMAL',
                statusColor: '#9C27B0',
                isSystem: 0,
                sortOrder: 3,   
                isActive: 1,
                remark: '已预约试听课程的客户'
            },
            {
                statusCode: '4',
                statusName: '试听完成',
                statusType: 'CUSTOM',
                parentType: 'NORMAL',
                statusColor: '#673AB7',
                isSystem: 0,
                sortOrder: 4,
                isActive: 1,
                remark: '已完成试听课程的客户'
            },
            {
                statusCode: '5',
                statusName: '考虑中',
                statusType: 'CUSTOM',
                parentType: 'NORMAL',
                statusColor: '#FF5722',
                isSystem: 0,
                sortOrder: 5,
                isActive: 1,
                remark: '试听后正在考虑是否报名的客户'
            },
            {
                statusCode: '6',
                statusName: '已报名',
                statusType: 'CUSTOM',
                parentType: 'NORMAL',
                statusColor: '#4CAF50',
                isSystem: 0,
                sortOrder: 6,
                isActive: 1,
                remark: '已成功报名缴费的客户'
            },
            {
                statusCode: '7',
                statusName: '正常上课',
                statusType: 'CUSTOM',
                parentType: 'NORMAL',
                statusColor: '#8BC34A',
                isSystem: 0,
                sortOrder: 7,
                isActive: 1,
                remark: '正在正常上课的学员'
            },
            {
                statusCode: '8',
                statusName: '即将结课',
                statusType: 'CUSTOM',
                parentType: 'NORMAL',
                statusColor: '#FFC107',
                isSystem: 0,
                sortOrder: 8,
                isActive: 1,
                remark: '课程即将结束的学员'
            }
        ];

        // 批量创建状态
        for (const status of predefinedStatuses) {
            try {
                await doInsert(status);
            } catch (error) {
                console.warn(`状态 ${status.statusName} 可能已存在:`, error);
            }
        }

        showSuccess('预定义状态初始化成功');
        fetchData();
    } catch (error) {
        console.error('初始化失败:', error);
        showError('初始化失败');
    }
}

// 导出Excel
async function handleExport() {
    try {
        await doExportExcel(queryParams);
        showSuccess('导出成功');
    } catch (error) {
        console.error('导出失败:', error);
        showError('导出失败');
    }
}

// 下载模板
async function handleDownloadTemplate() {
    try {
        await doDownloadTemplate();
        showSuccess('模板下载成功');
    } catch (error) {
        console.error('下载模板失败:', error);
        showError('下载模板失败');
    }
}

// 导入
function handleImport() {
    importDialog.value = true;
}

// 确认导入
async function confirmImport() {
    if (!uploadFile.value.length) {
        showError('请选择要导入的文件');
        return;
    }

    try {
        const formData = new FormData();
        formData.append('file', uploadFile.value[0]);
        
        const response = await doImportExcel(formData);
        if (response.code === 200) {
            showSuccess('导入成功');
            importDialog.value = false;
            uploadFile.value = [];
            fetchData();
        }
    } catch (error) {
        console.error('导入失败:', error);
        showError('导入失败');
    }
}

// 生命周期
onMounted(() => {
    fetchData();
});
</script>

<style lang="scss" scoped>
:deep(.v-data-table) {
    .v-data-table__td {
        padding: 8px 16px;
    }
}
</style> 